import 'package:common_utils/common_utils.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';
import 'package:xinxuan/http/http_util_service.dart';
import 'package:xinxuan/vo/address_list_vo.dart';
import 'package:xinxuan/vo/common_vo/common_address_item_vo.dart';
import 'package:xinxuan/vo/common_vo/common_pagination_vo.dart';
import 'package:xinxuan/vo/gift_list_vo.dart';

class GiftPageController extends GetxController {

  /// 提货数量
  var quantity = 0.obs;
  /// 赠品倍数
  int quantityMultiple = 6;
  /// 小计
  var price = '0.00'.obs;

  /// 商品列表
  var giftListVo = GiftListVo(
    data: [],
    meta: GiftMeta(
      pagination: CommonPagination(
        total: 0,
        currentPage: 1
      )
    )
  ).obs;

  /// 地址列表
  var addressItem = CommonAddressItem(id: 0).obs;

  @override
  void onReady() {
    getGiftList();
    getAddressList();
    super.onReady();
  }

  /// 获取商品列表
  getGiftList() async {
    GiftListVo tempVo = await HttpUtilService.getGiftList(page: giftListVo.value.meta!.pagination!.currentPage!);
    giftListVo.value = tempVo;
    update();
  }

  /// 获取收货地址列表
  getAddressList() async {
    AddressListVo addressListVo = await HttpUtilService.getAddressList();
    if (addressListVo.data!.length > 0) {
      addressItem.value = addressListVo.data![0];
      update();
    }
  }

  /// 修改数量
  changeQuantity(bool isAdd) {
    if (giftListVo.value.data!.length <= 0) {
      return;
    }
    if (isAdd) {
      int tempNum = quantity.value + quantityMultiple;
      if (tempNum > giftListVo.value.data![0].quantity!) {
        EasyLoading.showToast('数量不足，现数量${giftListVo.value.data![0].quantity!}');
        return;
      }
      quantity.value = tempNum;
    } else {
      if (quantity.value > quantityMultiple) {
        quantity.value = quantity.value - quantityMultiple;
      } else {
        if (quantity.value > 0) {
          EasyLoading.showToast('最低提货数量：$quantityMultiple');
        }
      }
    }

    var priceValue = NumUtil.multiplyDecStr(giftListVo.value.data![0].price!, '${quantity.value}');
    
    price.value = double.parse(priceValue.toString()).toString();

    update();
  }

  /// 提交发货
  submitShipment() async {
    if (addressItem.value.id! <= 0) {
      EasyLoading.showToast('请选择收货地址');
      return;
    }
    if (quantity.value < quantityMultiple) {
      EasyLoading.showToast('发货数量不足');
      return;
    }
    GiftItem giftItem = giftListVo.value.data![0];
    bool res = await HttpUtilService.submitGiftOrder(holderId: giftItem.id!, addressId: addressItem.value.id!, quantity: quantity.value);
    if (res) {
      Get.back();
      EasyLoading.showToast('提交成功');
    }
  }

}